/**
 *
 */
package cc.aileron.workflow.parameter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cc.aileron.accessor.PojoAccessor;
import cc.aileron.accessor.PojoAccessorValue;
import cc.aileron.workflow.WorkflowParameterBinder;

import com.google.inject.Singleton;

/**
 * WorkflowParameterBinder のデフォルト実装
 * 
 * @author aileron
 */
@Singleton
public class WorkflowParameterBinderDefault implements WorkflowParameterBinder
{
    /*
     * (非 Javadoc)
     * 
     * @see
     * cc.aileron.workflow.WorkflowParameterBinder#bind(cc.aileron.accessor.
     * PojoAccessor, java.util.Map)
     */
    @Override
    public <T> void bind(final PojoAccessor<T> accessor,
            final Map<String, Object> p, final List<String> keys)
            throws Exception
    {
        for (final String key : keys)
        {
            final Object rawValue = p.get(key);
            final Object value;
            final PojoAccessorValue accessorValue = accessor.to(key);
            if (rawValue != null
                    && List.class.isAssignableFrom(rawValue.getClass()) == false
                    && List.class.isAssignableFrom(accessorValue.type()))
            {
                final List<Object> list = new ArrayList<Object>();
                list.add(rawValue);
                value = list;
            }
            else
            {
                value = rawValue;
            }
            accessorValue.value(value);
        }
    }

}
